/**
 * 表格相关 Hook
 */

import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

export interface TableState {
  loading: boolean
  data: any[]
  total: number
  currentPage: number
  pageSize: number
  selection: any[]
}

export interface TableOptions {
  immediate?: boolean
  pageSize?: number
  showSelection?: boolean
  showIndex?: boolean
}

export function useTable<T = any>(
  fetchData: (params: any) => Promise<{ data: T[]; total: number }>,
  options: TableOptions = {}
) {
  const {
    immediate = true,
    pageSize = 10,
    showSelection = false,
    showIndex = false
  } = options

  // 表格状态
  const state = reactive<TableState>({
    loading: false,
    data: [],
    total: 0,
    currentPage: 1,
    pageSize,
    selection: []
  })

  // 查询参数
  const queryParams = ref<Record<string, any>>({})

  // 获取列表数据
  const getList = async () => {
    try {
      state.loading = true
      const params = {
        page: state.currentPage,
        size: state.pageSize,
        ...queryParams.value
      }
      
      const response = await fetchData(params)
      state.data = response.data
      state.total = response.total
    } catch (error) {
      ElMessage.error('获取数据失败')
      console.error('获取数据失败:', error)
    } finally {
      state.loading = false
    }
  }

  // 刷新数据
  const refresh = () => {
    state.currentPage = 1
    getList()
  }

  // 重置查询
  const resetQuery = () => {
    queryParams.value = {}
    refresh()
  }

  // 处理页码变化
  const handleCurrentChange = (page: number) => {
    state.currentPage = page
    getList()
  }

  // 处理页大小变化
  const handleSizeChange = (size: number) => {
    state.pageSize = size
    state.currentPage = 1
    getList()
  }

  // 处理选择变化
  const handleSelectionChange = (selection: any[]) => {
    state.selection = selection
  }

  // 删除单行
  const deleteRow = async (id: string, deleteApi: (id: string) => Promise<void>) => {
    try {
      await deleteApi(id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }

  // 批量删除
  const batchDelete = async (deleteApi: (ids: string[]) => Promise<void>) => {
    if (state.selection.length === 0) {
      ElMessage.warning('请选择要删除的数据')
      return
    }

    try {
      const ids = state.selection.map(item => item.id)
      await deleteApi(ids)
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      ElMessage.error('批量删除失败')
      console.error('批量删除失败:', error)
    }
  }

  // 计算属性
  const hasSelection = computed(() => state.selection.length > 0)
  const selectionCount = computed(() => state.selection.length)

  // 初始化
  if (immediate) {
    getList()
  }

  return {
    // 状态
    state,
    queryParams,
    
    // 计算属性
    hasSelection,
    selectionCount,
    
    // 方法
    getList,
    refresh,
    resetQuery,
    handleCurrentChange,
    handleSizeChange,
    handleSelectionChange,
    deleteRow,
    batchDelete
  }
}
